import 'dart:convert';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:day_night_switcher/day_night_switcher.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:get/get.dart';
import 'package:rename_exif/main_controller.dart';
import 'package:file_picker_desktop/file_picker_desktop.dart';
import 'tools.dart';
import 'config.dart';


class Menu extends StatelessWidget {
  const Menu({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var c = Get.find<MainController>();
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.only(left: 10, right: 10),
      // color: Colors.lightGreen,
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          MyIconButton(
            text: "添加文件",
            icon: Icons.library_add,
            onPressed: () async {
              showMyCupertinoDialog(context);
              try {
                final result = await pickFiles(
                  allowMultiple: true,
                  type: FileType.custom,
                  allowedExtensions: ['jpg', 'JPG', 'jpeg', 'JPEG'],
                );
                print("pickFiles: ${result?.paths}");
                c.walkFiles(result?.paths);
              } finally {
                Navigator.of(context).pop();
              }
            },
          ),
          MyIconButton(
            text: "添加目录",
            icon: Icons.create_new_folder,
            // onPressed: () async {
            //   showMyCupertinoDialog(context);
            //   try {
            //     var p = await getDirectoryPath(dialogTitle: "选择目录");
            //     c.walkDir(p);
            //   } finally {
            //     Navigator.of(context).pop();
            //   }
            // },
            onPressed: () => _openDirDialog(context),
          ), VD,
          MyIconButton(
            text: "清空",
            icon: Icons.cleaning_services_outlined,
            onPressed: () => c.clearAll(),
          ),VD,
          Obx(() => MyIconButton(
            text: "刷新预览",
            icon: Icons.autorenew,
            onPressed: c.refreshNewNameEnable() ? () {
              c.refreshNewName();
            } : null,
          )), VD,
          Obx(() => MyIconButton(
            text: "开始",
            icon: Icons.label,
            onPressed: c.runEnable() ? () async {
              showMyCupertinoDialog(context);
              try {
                print("run");
                // await Future.delayed( Duration(seconds: 10));
                c.start();
                print("run ending");
              } finally {
                Navigator.of(context).pop();
              }
            } : null,
          )),
          Expanded(child: Container()),
          MyIconButton(
            text: "关于",
            icon: Icons.view_compact_outlined,
            onPressed: () => _aboutDialog(context),
          ),
          const SizedBox(width: 10),
          const DarkModeSwitcher(),
      ]),
    );
  }

  _aboutDialog(BuildContext context) async {
      // 接收点击自己反参的值
      return await showDialog (
        context: context,
        barrierColor: Colors.blueGrey.withAlpha(30),
        barrierDismissible: true,
        builder: (context) => const AboutDialog()
      );
  }

  _openDirDialog(BuildContext context) async {
    var c = Get.find<MainController>();
    // 接收点击自己反参的值
    bool? recursive = await showDialog(
      context: context,
      barrierColor: Colors.blueGrey.withAlpha(30),
      barrierDismissible: true,
      builder: (context) => AlertDialog(
        title: Row(children: const [
          Icon(Icons.info_outline, size: 24, color: Colors.blueAccent),
          SizedBox(width: 10),
          Text( '是否递归查找文件?'),
        ]),
        // 稳定版暂时不支持
        // actionsAlignment: MainAxisAlignment.spaceEvenly,
        actions: <Widget>[
          TextButton(
            child: const Text('是'),
            onPressed: () => Navigator.of(context).pop(true),
          ),
          TextButton(
            child: const Text('否'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
        ],
      ),
    );
    print("recv: $recursive");
    if (recursive == null) { return; }

    showMyCupertinoDialog(context);
    try {
      var p = await getDirectoryPath(dialogTitle: "选择目录");
      c.walkDir(p, recursive);
    } finally {
      Navigator.of(context).pop();
    }
  }
}

class AboutDialog extends StatelessWidget {
  const AboutDialog({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SimpleDialog(
      title: const Text("关  于", textAlign: TextAlign.center),
      // 标题
      titlePadding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
      // 标题外间距
      // 标题样式 TextStyle
      titleTextStyle: Theme
          .of(context)
          .textTheme
          .headline5,
      contentPadding: const EdgeInsets.only(left: 5, right: 5),
      // 内容外间距
      // backgroundColor: Colors.white, // 背景色
      children: [
        const Divider(),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(flex: 1, child: _rightSide(context)),
            Expanded(flex: 1, child: _leftSide(context)),
        ]),
        const Divider(),
        TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("我知道了"),
            style: Theme.of(context).textButtonTheme.style
        ),
        const Divider(),
      ],
    );
  }

    Widget _leftSide(BuildContext context) {
      return Container(
        alignment: Alignment.topLeft,
        // width: double.infinity,
        // height: double.infinity,
        // color: Colors.cyan,
        padding: const EdgeInsets.only(left: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
          Text("特性:", style: Theme.of(context).textTheme.subtitle1?.copyWith(fontWeight: FontWeight.bold)),
          const SizedBox(height: 10),
          Text(feature, style: Theme.of(context).textTheme.bodyText1),
        ],),
      );
    }
    Widget _rightSide(BuildContext context) {
      return Column(children: [
        AboutText(title: "作者", value: Text(Author, style: Theme
            .of(context)
            .textTheme
            .bodyText2)),
        AboutText(title: "主页", value: RichText(
          text: TextSpan(
            text: Git,
            style: Theme.of(context).textTheme.bodyText2?.copyWith(color: Colors.blueAccent),
            recognizer: TapGestureRecognizer()..onTap = _launchURL,
          ),
        )),
        AboutText(title: "版本", value: Text(Version, style: Theme.of(context).textTheme.bodyText2)),
        AboutText(title: "时间", value: Text(Last, style: Theme.of(context).textTheme.bodyText2)),
        Container(
          height: 50,
          width: double.infinity,
          color: Colors.amber,
          padding: const EdgeInsets.only(top: 10, bottom: 10),
          margin: const EdgeInsets.only(top: 10, bottom: 5),
          child: _memoryImage(bmcImageBase64),
        ),
        SizedBox(
          height: 200,
          width: 200,
          child: _memoryImage(payImageBase64),
        ),
      ]);
    }

  Widget _memoryImage(String s) {
    if (s.length % 4 > 0) {
      s += '=' * (4 - s.length % 4); // as suggested by Albert221
    }
    var bytes = const Base64Decoder().convert(s);
    return Image.memory(bytes);
  }

  void _launchURL() async =>
      await canLaunch(Git) ? await launch(Git) : throw 'Could not launch $Git';

}

class AboutText extends StatelessWidget {
  final String title;//, value;
  final Widget value;

  const AboutText({Key? key, required this.title, required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const SizedBox(width: 10),
        Container(
          alignment: Alignment.centerRight,
          width: 60,
          child: Text("$title :", style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.redAccent),),
        ),
        const SizedBox(width: 10),
        // Text(value, style: TextStyle(fontSize: 14, color: Colors.redAccent)),
        value,
      ],
    );
  }
}



// ignore: must_be_immutable
class MyIconButton extends StatelessWidget {
  MyIconButton({Key? key, required this.text, required this.icon, this.onPressed}) : super(key: key);
  String text;
  IconData icon;
  VoidCallback? onPressed;
  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon),
            Text(text)
        ]
      )
    );
  }
}

class DarkModeSwitcher extends StatelessWidget {
  const DarkModeSwitcher({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var c = Get.find<MainController>();
    return SizedBox(
      width: 66,
      child: DayNightSwitcher(
        isDarkModeEnabled: c.isDarkModeEnabled.value,
        onStateChanged: (v) => c.onDarkModeStateChanged(v)
      ),
    );
  }
}

